package com.tax.config.filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 访问地址路径拦截配置
 */
@Configuration
public class FilterConfig extends WebMvcConfigurerAdapter {

    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new RequestWrapperFilter());
        registration.addUrlPatterns("/*");
        registration.setName("myInputStreamFilter");
        // 设置过滤器执行优先级，数值越小优先级越高
        // 当前只要保证Filter过滤器在Interceptor拦截器之前执行即可，所以设置为最低优先级
        registration.setOrder(Ordered.LOWEST_PRECEDENCE);
        return registration;
    }


    @Override
    public void  addInterceptors(InterceptorRegistry registry) {
        //拦截路径
        String[] addLoginPathPatterns = {"/tax-h5/login","tax/tax-pc/login"};
        //排除的路径
        String[] excludePathPatterns = {};
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns(addLoginPathPatterns).excludePathPatterns(excludePathPatterns);

        String[] addAuthPathPatterns = {"/user/*"};
        String[] excludeAuthPathPatterns = {};
        registry.addInterceptor(new UserInterceptor()).addPathPatterns(addAuthPathPatterns).excludePathPatterns(excludeAuthPathPatterns);
    }


    /**
     * 解决跨域问题
     */
    /*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("Content-Type,X-Requested-With,Cookies,Cookie,X-Auth-Token,token,auth,Authorization")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600);
    }*/

    /*@Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 请求常用的三种配置，*代表允许所有，当时你也可以自定义属性（比如header只能带什么，method只能是post方式等等）
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("Content-Type,X-Requested-With,Cookies,Cookie,X-Auth-Token,token,auth,Authorization");
        corsConfiguration.addAllowedMethod("GET,POST,PUT,DELETE,OPTIONS");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }*/
}
